package com.example.partner.activity.find;

import static android.content.ContentValues.TAG;
import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.partner.R;
import com.example.partner.activity.home.UserInfoActivity;
import com.example.partner.activity.home.UserListActivity;
import com.example.partner.adapter.find.CommentAdapter;
import com.example.partner.adapter.find.ImageAdapter;
import com.example.partner.adapter.find.PostImageAdapter;
import com.example.partner.adapter.user.UserAdapter;
import com.example.partner.common.BaseResponse;
import com.example.partner.common.Page;
import com.example.partner.model.domain.User;
import com.example.partner.model.request.PostCommentAddRequest;
import com.example.partner.model.vo.PostCommentVO;
import com.example.partner.model.vo.PostVo;
import com.example.partner.service.FollowService;
import com.example.partner.service.PostService;
import com.example.partner.service.UserService;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PostDetailActivity extends AppCompatActivity {

    private TextView textViewAuthorName;
    private ViewPager2 viewPagerImages;
    private Boolean isFollow = false;

    private TextView textViewTitle;
    private TextView textViewContent;
    private TextView textViewLikeCount;
    private TextView textViewCommentCount;
    private ImageView imageViewAuthorAvatar;
    private ImageView imageViewLikeIcon;
    private RecyclerView recyclerViewComments;
    private CommentAdapter commentAdapter;
    private PostImageAdapter imagesAdapter;

    EditText editTextComment ;
    Button buttonSendComment;

    Button followButton;
    private List<PostCommentVO> commentList = new ArrayList<>();
    //帖子图片
    private List<String> images = new ArrayList<>();

    private PostService postService;
    private FollowService followService;
    private SwipeRefreshLayout swipeRefreshLayout;

    private UserService userService;

    private Long loginId;

    private Long postUserId;
    private Retrofit retrofit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        // 获取传递的 postId
        Long postId = getIntent().getLongExtra("postId", -1);
        // 初始化 postService
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)  // 请确保你有正确的 BASE_URL
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        postService = retrofit.create(PostService.class);
        followService = retrofit.create(FollowService.class);
        userService = retrofit.create(UserService.class);
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        loginId = sharedPreferences.getLong("userId", -1);        // 初始化控件
        textViewAuthorName = findViewById(R.id.textViewAuthorName);
        textViewTitle = findViewById(R.id.textViewTitle);
        textViewContent = findViewById(R.id.textViewContent);
        textViewLikeCount = findViewById(R.id.textViewLikeCount);
        textViewCommentCount = findViewById(R.id.textViewCommentCount);
        imageViewLikeIcon = findViewById(R.id.imageViewLikeIcon);
        recyclerViewComments = findViewById(R.id.recyclerViewComments);
        imageViewAuthorAvatar = findViewById(R.id.imageViewAuthorAvatar);
        editTextComment = findViewById(R.id.editTextComment);
        buttonSendComment = findViewById(R.id.buttonSendComment);
        followButton = findViewById(R.id.buttonFollow);
        // 设置 RecyclerView 的 LayoutManager（水平滑动）
        LinearLayoutManager layoutManagerImages = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        LinearLayoutManager layoutManagerComments = new LinearLayoutManager(this);
        recyclerViewComments.setLayoutManager(layoutManagerComments);
        // 设置适配器（这里的适配器需要根据你的实际情况进行定制）
        imagesAdapter = new PostImageAdapter(this,images);
        commentAdapter = new CommentAdapter(this,commentList,new ArrayList<>());
        recyclerViewComments.setAdapter(commentAdapter);
        // 初始化 ViewPager2
        viewPagerImages = findViewById(R.id.viewPagerImages);
        imagesAdapter = new PostImageAdapter(this,images);
        viewPagerImages.setAdapter(imagesAdapter);
        fetchPostDetails(postId);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            refreshData();
        });
        final int delayMillis = 3000;  // 设置切换间隔时间，单位毫秒
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int currentItem = viewPagerImages.getCurrentItem();
                if (images.size() > 0) {
                    int nextItem = (currentItem + 1) % images.size();
                    viewPagerImages.setCurrentItem(nextItem);
                    handler.postDelayed(this, delayMillis);
                    // 其他操作
                }

            }
        };

        // 开始自动轮播
        handler.postDelayed(runnable, delayMillis);
        buttonSendComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取用户输入的评论内容
                String commentContent = editTextComment.getText().toString();
                PostCommentAddRequest postComment = new PostCommentAddRequest();
                // 获取传递的 postId
                Long postId = getIntent().getLongExtra("postId", -1);
                postComment.setPostId(postId);
                postComment.setContent(commentContent);
                SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
                Long userId = sharedPreferences.getLong("userId", -1);
                postComment.setUserId(userId);
                // 在这里执行发送评论的逻辑，可以将评论内容提交到服务器等
                addComment(postComment);
                Toast.makeText(getApplicationContext(), "评论成功", Toast.LENGTH_SHORT).show();
                // 清空评论输入框
                editTextComment.setText("");
            }
        });
        viewPagerImages.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {

            }
        });
        followButton.setOnClickListener(v -> {
            // Call your method to check if the user is followed or not
            submitFollow(postUserId);
        });
        imageViewAuthorAvatar.setOnClickListener(v->{
            showUserInfo();
        });
    }
    private void showUserInfo(){
        userService.getCurrentUser(postUserId).enqueue(new Callback<BaseResponse<User>>() {
            @Override
            public void onResponse(Call<BaseResponse<User>> call, Response<BaseResponse<User>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    User user = response.body().getData();
                    // 更新UI或处理数据
                    Intent userInfoIntent = new Intent(PostDetailActivity.this, UserInfoActivity.class);
                    userInfoIntent.putExtra("userAccount", user.getUserAccount());
                    userInfoIntent.putExtra("username", user.getUsername());
                    userInfoIntent.putExtra("avatarUrl", user.getAvatarUrl());
                    userInfoIntent.putExtra("selectedUserId", user.getId());

                    // Start UserInfoActivity to display user info
                    startActivity(userInfoIntent);
                } else {
                    // 处理错误情况
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<User>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });

    }

    /**
     * 添加评论
     * @param postCommentAddRequest
     */
    private void addComment(PostCommentAddRequest postCommentAddRequest){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService postService = retrofit.create(PostService.class);
        Call<BaseResponse<Boolean>> call = postService.addPostComment(postCommentAddRequest);
        call.enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean> >call, Response<BaseResponse<Boolean>> response) {
                if (response.isSuccessful()) {
                    Boolean data = response.body().getData();
                    commentAdapter.notifyDataSetChanged();
                } else {
                    // 处理错误情况
                    Log.d(TAG, "onResponse:fail");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean> >call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }
    // Inside your class or method

    /**
     * 获取初始数据
     * @param postId
     */
    private void fetchPostDetails(Long postId) {
        Call<BaseResponse<PostVo>> call = postService.queryPostById(postId,loginId);
        call.enqueue(new Callback<BaseResponse<PostVo>>() {
            @Override
            public void onResponse(Call<BaseResponse<PostVo>> call, Response<BaseResponse<PostVo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    PostVo postVo = response.body().getData();
                    initializeViews(postVo);
                } else {
                    // Handle error
                    Toast.makeText(PostDetailActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<PostVo>> call, Throwable t) {
                // Handle failure
                Toast.makeText(PostDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 初始化
     * @param postVo
     */
    private void initializeViews(PostVo postVo) {
        textViewLikeCount.setText(String.valueOf(postVo.getPost().getLiked()));
        textViewCommentCount.setText(String.valueOf(postVo.getPost().getComments()));
        textViewAuthorName.setText(postVo.getCreateUser().getUsername());
        textViewTitle.setText(postVo.getPost().getTitle());
        textViewContent.setText(postVo.getPost().getContent());
        Boolean isLiked = postVo.getPost().getLike();
        imageViewLikeIcon.setImageResource(isLiked != null && isLiked ? R.drawable.ic_like_hightlight : R.drawable.ic_like);
        // 加载头像
        if (postVo.getCreateUser().getAvatarUrl() != null) {
            String avatarUrl = postVo.getCreateUser().getAvatarUrl();
            postUserId = postVo.getCreateUser().getId();
            loadAvatarIntoImageView(avatarUrl);
        }
        ArrayList<String> urls = null;
        if (postVo.getPost().getAvatarUrl() != null){
            String[] strings = postVo.getPost().getAvatarUrl().split(",");
            urls = new ArrayList<>(Arrays.asList(strings));
        }
        imagesAdapter.setData(urls);
        commentList = postVo.getPostCommentList();
        followOrNot(postUserId,loginId);
        // 使用 Lambda 表达式筛选出 pid 为 id 的最高级回复
        List<PostCommentVO> topLevelReplies = commentList.stream()
                .filter(comment -> comment.getPid() == postVo.getPost().getUserId())
                .collect(Collectors.toList());
        commentAdapter.setData(topLevelReplies,commentList);
        commentAdapter.notifyDataSetChanged();
    }

    /**
     * 加载头像
     * @param avatarUrl
     */
    private void loadAvatarIntoImageView(String avatarUrl) {
        // 使用 Glide 加载头像
        Glide.with(this)
                .load(avatarUrl)
                .apply(new RequestOptions().circleCrop())  // 如果需要显示为圆形头像
                .into(imageViewAuthorAvatar);  // 替换成你的头像 ImageView
    }
    /**
     * 刷新数据，重新加载
     */
    private void refreshData() {
        // 获取传递的 postId
        Long postId = getIntent().getLongExtra("postId", -1);
        commentList.clear();
       fetchPostDetails(postId);
        commentAdapter = new CommentAdapter(this,commentList,new ArrayList<>());
        recyclerViewComments.setAdapter(commentAdapter);
        swipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 判断用户是否关注博主
     * @param userId
     * @param loginUserId
     */
    private void followOrNot(Long userId,Long loginUserId) {

        followService.isFollow(userId,loginUserId).enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    isFollow = response.body().getData();
                    if (isFollow){
                        followButton.setText("取消关注");
                    }
                    // 更新UI或处理数据
                } else {
                    // 处理错误情况
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });

    }

    /**
     * 提交关注
     * @param userId
     */
    private void submitFollow(Long userId) {

        followService.follow(userId,loginId,isFollow).enqueue(new Callback<BaseResponse<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    if (response.body().data && isFollow == false){
                        // 创建AlertDialog
                        new AlertDialog.Builder(PostDetailActivity.this)
                                .setTitle("关注") // 设置对话框标题
                                .setMessage("关注成功") // 设置要显示的消息
                                .setPositiveButton("确定", (dialog, which) -> {
                                    // 用户点击确定按钮后的操作
                                })
                                .show();
                        isFollow = true;
                        followButton.setText("取消关注");

                    }else {
                        new AlertDialog.Builder(PostDetailActivity.this)
                                .setTitle("取消关注") // 设置对话框标题
                                .setMessage("已取消关注") // 设置要显示的消息
                                .setPositiveButton("知道了", (dialog, which) -> {
                                    // 用户点击确定按钮后的操作
                                })
                                .show();
                        isFollow = false;
                        followButton.setText("关注");

                    }

                    // 更新UI或处理数据
                } else {
                    // 处理错误情况
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });


    }
}
